/*
 * Filename:    WorkFlowServiceImpl.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年10月29日
 */
package com.paic.mhis.hcpms.trust.biz.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.core.auth.biz.service.Authority;
import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.agreement.healthcareprovider.util.HttpProcessUtil;
import com.paic.mhis.hcpms.common.workflow.vo.HcpmsWorkFlowVO;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityMedicalService;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityWFService;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityWorkFlowService;
import com.paic.mhis.hcpms.trust.util.TrustConstants;
import com.paic.pafa.exceptions.BusinessException;

@Component("integrityWorkFlowService")
public class IntegrityWorkFlowServiceImpl implements IntegrityWorkFlowService {
	@Autowired
	private IntegrityWFService integrityWFService;

	// @Autowired
	// private InsuredMedicalDetailService insuredMedicalDetailService;

	@Autowired
	private IntegrityMedicalService integrityMedicalService;

	@Override
	public String startWorkFlow(String warnNo, UserDetails user, Map<String, String> condition) throws Exception {
		HcpmsWorkFlowVO vo = new HcpmsWorkFlowVO();
		if (user != null) {
			List<Authority> authorityList = user.getAuthorities();
			List<String> role = new ArrayList<String>();
			for (Authority authority : authorityList) {
				role.add(authority.getAuthority());
			}
			vo.setRole(role);
			vo.setActCurrent(user.getUsername());
			vo.setAssigner(user.getUsername());
		}
		vo.setTaskNo(warnNo);
		vo.setTaskType(TrustConstants.TASK_TYPE);
		vo.setParamValue(condition);
		return integrityWFService.startProcess(vo).getActCurrent();
	}

	@Override
	public String processWorkFlow(HcpmsWorkFlowVO vo) throws Exception {
		vo.setTaskType(TrustConstants.TASK_TYPE);
		return integrityWFService.processFlow(vo).getActCurrent();
	}

	@Override
	public String vilidateOrBindUser(String warnNo, String username, String status) {
		if (StringUtils.isBlank(warnNo) || StringUtils.isBlank(username) || StringUtils.isBlank(status)) {
			return TrustConstants.PROCESS_OUT_POWER;
		}
		HcpmsWorkFlowVO vo = new HcpmsWorkFlowVO();
		vo.setTaskNo(warnNo);
		vo.setActCurrent(username);
		vo.setActNo(status);
		vo.setTaskType(TrustConstants.TASK_TYPE);
		String processState = integrityWFService.vilidateOrBindUser(vo);
		return processState;
	}

	@Transactional
	@Override
	public Map<String, Object> resultMapIntegrityWorkFlow(JSONObject transferJson, Map<String, Object> paramMap,
			Map<String, Object> resultMap) throws BusinessException {
		String taskNo = (String) paramMap.get("taskNo");// 任务编号
		String status = (String) paramMap.get("status");// 当前节点状态
		String saveStatus = (String) paramMap.get("saveStatus");// 操作状态1.保存，2.暂存
		UserDetails user = (UserDetails) paramMap.get("userInfo");// 用户对象
		// 操作权限的绑定和查询操作权限
		if (StringUtils.isEmpty(taskNo) && StringUtils.isEmpty(status) && StringUtils.isEmpty(user.getUsername())) {
			String processState = this.vilidateOrBindUser(taskNo, user.getUsername(), status);
			if (TrustConstants.PROCESS_NOT_POWER.endsWith(processState)) {
				resultMap.put(TrustConstants.STATE_KEY, TrustConstants.SUCCESS_STATE_VALUE);
				resultMap.put(TrustConstants.MSG_KEY, TrustConstants.PROCESS_NOT_POWER_ERROR);
				return resultMap;
			} else if (TrustConstants.PROCESS_OUT_POWER.endsWith(processState)) {
				resultMap.put(TrustConstants.STATE_KEY, TrustConstants.SUCCESS_STATE_VALUE);
				resultMap.put(TrustConstants.MSG_KEY, TrustConstants.PROCESS_OUT_POWER_ERROR);
				return resultMap;
			}
		}
		// 保存及暂存业务方法调用
		resultMap = this.resultMapBusiness(transferJson, saveStatus, user.getUsername(), resultMap, taskNo);
		if (StringUtils.isEmpty(taskNo)) {
			taskNo = (String) resultMap.get("taskNo");
		}
		// 启动流程
		try {
			this.startWorkFlow(taskNo, user, null);
			if (TrustConstants.STATUS_SAVE.equals(saveStatus) || TrustConstants.STATUS_BATCH.equals(saveStatus)) {
				// 提交
				HcpmsWorkFlowVO wfvo = new HcpmsWorkFlowVO();
				wfvo.setTaskNo(taskNo);// 设置任务启动Id
				wfvo.setActCurrent(user.getUsername());// 将当前处理人Id设为当前登录者的用户名
				this.processWorkFlow(wfvo);// 获取流转流程的当前节点
			}
		} catch (Exception e) {
			resultMap = HttpProcessUtil.processException(e);
		}
		resultMap.put(TrustConstants.STATE_KEY, TrustConstants.SUCCESS_STATE_VALUE);
		resultMap.put(TrustConstants.MSG_KEY, TrustConstants.SAVE_SUCCESS);
		resultMap.put(TrustConstants.RESULT_BUSINESS_KEY, taskNo);
		return resultMap;
	}

	@Transactional
	@Override
	public Map<String, Object> resultMapIntegrityAuditApproveWorkFlow(JSONObject transferJson,
			Map<String, Object> paramMap, Map<String, Object> resultMap) throws BusinessException {
		String taskNo = (String) paramMap.get("taskNo");// 任务编号
		transferJson.put("taskNo", taskNo);
		String status = (String) paramMap.get("status");// 当前节点状态
		String saveStatus = (String) paramMap.get("saveStatus");// 操作状态1.审核，2.审核批量,3.审批,4.审批批量
		UserDetails user = (UserDetails) paramMap.get("userInfo");// 用户对象
		String opinion = (String) paramMap.get("integrityOpinion");// 操作状态01.同意，02.不同意
		// 操作权限的绑定和查询操作权限
		if (StringUtils.isEmpty(taskNo) && StringUtils.isEmpty(status) && StringUtils.isEmpty(user.getUsername())) {
			String processState = this.vilidateOrBindUser(taskNo, user.getUsername(), status);
			if (TrustConstants.PROCESS_NOT_POWER.endsWith(processState)) {
				resultMap.put(TrustConstants.STATE_KEY, TrustConstants.SUCCESS_STATE_VALUE);
				resultMap.put(TrustConstants.MSG_KEY, TrustConstants.PROCESS_NOT_POWER_ERROR);
				return resultMap;
			} else if (TrustConstants.PROCESS_OUT_POWER.endsWith(processState)) {
				resultMap.put(TrustConstants.STATE_KEY, TrustConstants.SUCCESS_STATE_VALUE);
				resultMap.put(TrustConstants.MSG_KEY, TrustConstants.PROCESS_OUT_POWER_ERROR);
				return resultMap;
			}
		}
		// 审核、审批业务方法调用
		resultMap = this.resultMapAuditApproveBusiness(transferJson, saveStatus, user.getUsername(), resultMap);
		// 启动流程
		try {
			HcpmsWorkFlowVO wfvo = new HcpmsWorkFlowVO();
			wfvo.setTaskNo(taskNo);
			wfvo.setActCurrent(user.getUsername());
			wfvo.setActNo(status);
			// wfvo.setRole();
			Map<String, String> condition = new HashMap<String, String>();
			if (TrustConstants.STATUS_AUDIT.equals(saveStatus)) {// 1审核
				condition.put(TrustConstants.AUDIT_OPINION, opinion);
			} else if (TrustConstants.STATUS_APPROVE.equals(saveStatus)) {// 3.审批
				condition.put(TrustConstants.APPROVE_OPINION, opinion);
			}
			wfvo.setParamValue(condition);
			this.processWorkFlow(wfvo);
		} catch (Exception e) {
			resultMap = HttpProcessUtil.processException(e);
		}
		resultMap.put(TrustConstants.STATE_KEY, TrustConstants.SUCCESS_STATE_VALUE);
		resultMap.put(TrustConstants.MSG_KEY, TrustConstants.SAVE_SUCCESS);
		resultMap.put(TrustConstants.RESULT_BUSINESS_KEY, taskNo);
		return resultMap;
	}

	/**
	 * 医务人员暂存、保存前业务方法调用
	 * 
	 * @param transferJson
	 * @param saveStatus
	 * @param userName
	 * @param resultMap
	 * @return
	 * @throws BusinessException
	 */
	@Transactional
	private Map<String, Object> resultMapBusiness(JSONObject transferJson, String saveStatus, String userName,
			Map<String, Object> resultMap, String taskNo) throws BusinessException {
		if (TrustConstants.STATUS_SCRATCH.equals(saveStatus)) {// 2暂存
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userName", userName);
			resultMap = integrityMedicalService.updateStorageSaveDatePoint(transferJson, paramMap);
		} else if (TrustConstants.STATUS_SAVE.equals(saveStatus)) {// 1保存
			resultMap = integrityMedicalService.saveIntegrityDoctor(transferJson, userName);
		} else if (TrustConstants.STATUS_BATCH.equals(saveStatus)) {// 3.批量
			integrityMedicalService.saveIntegrityDoctorBatch(transferJson, userName, taskNo);
		}
		return resultMap;
	}

	/**
	 * 医务人员审核、审批业务方法调用
	 * 
	 * @param transferJson
	 * @param saveStatus
	 * @param userName
	 * @param resultMap
	 * @return
	 * @throws BusinessException
	 */
	@Transactional
	private Map<String, Object> resultMapAuditApproveBusiness(JSONObject transferJson, String saveStatus,
			String userName, Map<String, Object> resultMap) throws BusinessException {
		if (TrustConstants.STATUS_AUDIT.equals(saveStatus)) {// 1审核
			resultMap = this.resultMapOpinion(transferJson, resultMap);
		} else if (TrustConstants.STATUS_AUDITS.equals(saveStatus)) {// 2审核批量
			resultMap = this.resultMapOpinionBatch(transferJson, resultMap);
		} else if (TrustConstants.STATUS_APPROVE.equals(saveStatus)) {// 3.审批
			resultMap = resultMapOpinion(transferJson, resultMap);
			// 流程结束 扣分信息转移
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("warnNo", transferJson.getString("taskNo"));
			param.put("userName", userName);
			integrityMedicalService.addIntegrityPointTemps(param);
		} else if (TrustConstants.STATUS_APPROVES.equals(saveStatus)) {// 4.审批批量

		}
		return resultMap;
	}

	/**
	 * 操作执行单条
	 * 
	 * @param transferJson
	 * @param resultMap
	 * @return
	 */
	@Transactional
	private Map<String, Object> resultMapOpinion(JSONObject transferJson, Map<String, Object> resultMap) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 保存意见
		integrityMedicalService.saveAuditOpinion(this.paramOpinion(transferJson, paramMap));
		return resultMap;
	}

	/**
	 * 操作执行批量
	 * 
	 * @param transferJson
	 * @param resultMap
	 * @return
	 * @throws BusinessException
	 */
	private Map<String, Object> resultMapOpinionBatch(JSONObject transferJson, Map<String, Object> resultMap) {
		// String taskNos = transferJson.getString("taskNo");
		// taskNos = taskNos.substring(0, taskNos.length() - 1);
		// String[] taskNoAry = taskNos.split(",");
		// String opinionType = transferJson.getString("opinionType");
		// String opinion = transferJson.getString("opinion");
		// String opinionDesc = transferJson.getString("opinionDesc");
		// String createBy = transferJson.getString("createBy");
		// List<Map<String, String>> paramList = new ArrayList<Map<String,
		// String>>();
		// for (int i = 0; i < taskNoAry.length; i++) {
		// String tempTaskNo = taskNoAry[i];
		// Map<String, String> tempParmMap = new HashMap<String, String>();
		// tempParmMap.put("taskNo", tempTaskNo);
		// tempParmMap.put("opinionType", opinionType);
		// tempParmMap.put("opinion", opinion);
		// tempParmMap.put("opinionDesc", opinionDesc);
		// tempParmMap.put("createBy", createBy);
		// paramList.add(tempParmMap);
		// }
		// // 保存意见
		// integrityMedicalService.saveAuditBatchOpinion(paramList);
		return resultMap;
	}

	/**
	 * 加载参数
	 * 
	 * @param transferJson
	 * @param paramMap
	 * @return
	 */
	private Map<String, Object> paramOpinion(JSONObject transferJson, Map<String, Object> paramMap) {
		paramMap.put("taskNo", transferJson.getString("taskNo"));
		paramMap.put("opinionType", transferJson.getString("opinionType"));
		paramMap.put("opinion", transferJson.getString("opinion"));
		paramMap.put("opinionDesc", transferJson.getString("opinionDesc"));
		paramMap.put("createBy", transferJson.getString("createBy"));
		return paramMap;
	}
}
